using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace first_project
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        SpriteFont fontArial;
        Player player1;

        List<Asteroid> asteroidList;

        private int numAsteroids;
        private int maxAsteroids;
        private bool gameOver;
        private bool spawnAsteroid;
        private double lastAsteroidTime;
        private double asteroidIntervalTime;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            Window.Title = "JOGO";
            graphics.PreferredBackBufferWidth = 1024;
            graphics.PreferredBackBufferHeight = 768;
            graphics.ApplyChanges();
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            fontArial = Content.Load<SpriteFont>(@"fonts/Arial");

            player1 = new Player(Content.Load<Texture2D>("images/playerImg"), Content.Load<Texture2D>("images/quad"), Window);
            player1.Position = new Vector2(200, 200);

            this.asteroidList = new List<Asteroid>();
            asteroidIntervalTime = 5;
            numAsteroids = 0;
            maxAsteroids = 10;
            spawnAsteroid = true;
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                this.Exit();

            if (!gameOver)
            {
                Random randomNum = new Random();
                if (gameTime.TotalGameTime.TotalSeconds.CompareTo(lastAsteroidTime + asteroidIntervalTime) > 0 && spawnAsteroid)
                {
                    asteroidList.Add(new Asteroid(Window, Content.Load<Texture2D>("images/asteroidImg"), randomNum.Next(3, 5)));
                    lastAsteroidTime = gameTime.TotalGameTime.TotalSeconds;
                    numAsteroids++;
                    if (numAsteroids >= maxAsteroids)
                    {
                        spawnAsteroid = false;
                    }
                }

                player1.Update(gameTime);

                testCollision();

                foreach (Asteroid asteroid in asteroidList)
                {
                    asteroid.Update(gameTime);
                }
            }
            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.Black);

            spriteBatch.Begin();

            if (!gameOver)
            {
                player1.Draw(spriteBatch);
                foreach (Asteroid asteroid in asteroidList)
                {
                    asteroid.Draw(spriteBatch);
                }
            }
            else
            {
                string gameOverText = "GAME OVER";
                Vector2 textSize = fontArial.MeasureString(gameOverText); 
                spriteBatch.DrawString(fontArial, gameOverText, new Vector2(Window.ClientBounds.Width / 2, Window.ClientBounds.Height / 2) - textSize / 2, Color.Red);
            }
            spriteBatch.End();

            base.Draw(gameTime);

        }

        private void testCollision()
        {
            List<Asteroid> asteroidRemoveList = new List<Asteroid>();
            List<Asteroid> asteroidAddList = new List<Asteroid>();
            List<Shot> removedShots = new List<Shot>();

            foreach (Asteroid asteroid in asteroidList)
            {
                if (asteroid.CollisionRectangle.Intersects(player1.CollisionRectangle))
                {
                    gameOver = true;
                }
                foreach (Shot shot in player1.ShotList)
                {
                    if(asteroid.CollisionRectangle.Intersects(shot.CollisionRectangle))
                    {
                        removedShots.Add(shot);
                        if (asteroid.processShotColision())
                        {
                            asteroidRemoveList.Add(asteroid);
                        }
                        else
                        {
                            asteroidAddList.Add(new Asteroid(Window, Content.Load<Texture2D>("images/asteroidImg"), asteroid.Position, asteroid.Life));
                        }
                    }
                }
            }

            foreach (Asteroid asteroid in asteroidAddList)
            {
                asteroidList.Add(asteroid);
            }
            foreach (Asteroid asteroid in asteroidRemoveList)
            {
                asteroidList.Remove(asteroid);
            }
            foreach (Shot shot in removedShots)
            {
                player1.ShotList.Remove(shot);
            }
        }
    }
}
